
"""
    请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ，验证已经填入的数字是否有效即可。
    数字 1-9 在每一行只能出现一次。
    数字 1-9 在每一列只能出现一次。
    数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。（请参考示例图）
    注意：
    一个有效的数独（部分已被填充）不一定是可解的。
    只需要根据以上规则，验证已经填入的数字是否有效即可。
    空白格用 '.' 表示。
"""
from typing import List

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:

        # 用于判断行列是否重复
        def judge(tag):
            for a in range(0, 9):
                dic = {}
                for b in range(0, 9):
                    if tag =='L':#按列判断
                        if board[b][a] == '.':
                            continue
                        if board[b][a] in dic.keys():
                            return -1  # 列有重复值
                        else:
                            dic[board[b][a]] = 1

                    else:   #按行判断
                        if board[a][b]=='.':
                            continue
                        if board[a][b] in dic.keys():
                            return -1 #行有重复值
                        else:
                            dic[board[a][b]] = 1
            return 1 #行或者列没有重复值


        # 判断行是否重复
        result1 = judge('H')
        if result1 == -1:
            return False
            # 判断列是否重复
        result2 = judge('L')
        if result2 == -1:
            return False

        # 判断3X3是否重复
        for i in (1,4,7):
            for j in (1,4,7):
                dic = {}
                for m in range(i-1,i+1+1):
                    for n in range(j-1,j+1+1):
                        if board[m][n] =='.':
                            continue
                        if board[m][n] in dic.keys():
                            return False
                        else:
                            dic[board[m][n]] = 1
        return True
"""
#力扣解法
class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        rd = [set() for _ in range(9)]
        cd = [set() for _ in range(9)]
        ss = [set() for _ in range(9)]
        for i in range(9):
            for j in range(9):
                c = board[i][j]
                if c != '.':
                    if c in rd[i] or c in cd[j] or c in ss[3*(i//3) + (j//3)]:
                        return False
                    else:
                        rd[i].add(c)
                        cd[j].add(c)
                        ss[3*(i//3) + (j//3)].add(c)
        return True
"""
res = Solution().isValidSudoku([
    ["5","3",".",".","7",".",".",".","."],
    ["6",".",".","1","9","5",".",".","."],
    [".","9","8",".",".",".",".","6","."],
    ["8",".",".",".","6",".",".",".","3"],
    ["4",".",".","8",".","3",".",".","1"],
    ["7",".",".",".","2",".",".",".","6"],
    [".","6",".",".",".",".","2","8","."],
    [".",".",".","4","1","9",".",".","5"],
    [".",".",".",".","8",".",".","7","9"]])
print(res)